//
//  OAuthViewController.swift
//  XYWeibo
//
//  Created by 常晓璇 on 6/28/15.
//  Copyright © 2015 chang xiaoxuan. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,  UIWebViewDelegate{

    // 定义常量 
    
    private let WB_Client_ID = "1178514292"
    private let WB_Redirect_URL = "http://www.baidu.com"
    private let WB_Redirect_URLs = "https://www.baidu.com"
    private let WB_App_Secret = "93e33589e106c2d991fcd1ad75f64392"
    // 1.weiView 加载授权页面
    var webView: UIWebView?
    
    // 创造视图层次结构的方法
    override func loadView() {
        webView = UIWebView()
        webView?.delegate = self
        
        // 根视图就是 webView
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载授权页面
        loadOAuthPage()
    }
    
///  UIWebViewDelegate
    
    // 在ios开发中 代理方法返回true 表示一切正常 如果返回false 表示什么也发生
    
 /**
    
    初始
    https://api.weibo.com/oauth2/authorize?client_id=1178514292&redirect_uri=http://www.baidu.com
    
    登录成功
    https://api.weibo.com/oauth2/authorize
    
    授权成功 - 授权码
    https://www.baidu.com/?code=8846bd0d65b153089238cd20215a950c
    
    取消授权
    https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    
    如果是新浪的 URL  就继续加载
    如果是回调地址 需要根据URL中的内容 判断是否有授权码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request)
        
        // 获取URL的完整字符串
        let urlString = request.URL!.absoluteString
//        print(urlString)
        
        // 如果是新浪(不是回调)的 URL  就继续加载
        if !urlString .hasPrefix(WB_Redirect_URL) {
            return true
        }
        // 如果是回调地址 需要根据URL中的内容 判断是否有授权码
//        print("需要判断")
        let query = request.URL!.query!
        let codeStr = "code="
        
        if query.hasPrefix(codeStr) {
            let code = (query as NSString).substringFromIndex((codeStr as NSString).length)
//            print("获取授权码\(code)")
            loadAccessToken(code)
            SVProgressHUD.dismiss()
        } else {
//            print("取消授权")
            close()
        }
        
        return false
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL)"
        // ! 表示一定能生成
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    ///  使用授权码加载token
    private func loadAccessToken(code: String) {
        // 1.urlString
    
        let urlString = "oauth2/access_token"
        // 2.请求参数
        let params = ["client_id" : WB_Client_ID,
            "client_secret" : WB_App_Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : WB_Redirect_URL]
        
        // 3.发起网络请求
        NetworkTools.shareNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
            
            // 字典转模型 -> 加载用户信息 , 链式调用 
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
                if account != nil {
//                    print(account)
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            
//            // 归档保存
//            account.saveAccount()
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
}